package com.quan.commons.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 该类提供Quartz的cron表达式与Date之间的转换
 *
 * @author yhaoquan
 */
public class CronDateUtils {

    private static final String CRON_DATE_FORMAT = "ss mm HH dd MM ? yyyy";

    /**
     * 每年
     */
    private static final String CRON_DATE_FORMAT_EVERY = "ss mm HH dd MM ? *";

    /**
     * 将日期转换为Quartz Cron表达式
     *
     * @param date cron类型的日期
     * @return
     */
    public static String getCron(final Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(CRON_DATE_FORMAT);
        String formatTimeStr = "";
        if (date != null) {
            formatTimeStr = sdf.format(date);
        }
        return formatTimeStr;
    }

    /**
     * 将字符串日期转换为quartz表达式Cron
     *
     * @param datetime
     * @return
     * @throws ParseException
     */
    public static String getCron(String datetime) {
        try {
            Date dt = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm").parse(datetime);
            Calendar sc = Calendar.getInstance();
            sc.setTime(dt);
            return sc.get(Calendar.MINUTE) + " " + sc.get(Calendar.SECOND) + " " + sc.get(Calendar.HOUR_OF_DAY) + " " + sc.get(Calendar.DAY_OF_MONTH) + " " + (sc.get(Calendar.MONTH) + 1) + " ? " + (sc.get(Calendar.YEAR));
        } catch (ParseException e) {
            throw new RuntimeException("传入的日期格式不正确！");
        }
    }

    /***
     *
     * @param cron Quartz cron的类型的日期
     * @return Date日期
     */
    public static Date getDate(final String cron) {
        if (cron == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(CRON_DATE_FORMAT);
        Date date = null;
        try {
            date = sdf.parse(cron);
        } catch (ParseException e) {
            return null;// 此处缺少异常处理,自己根据需要添加
        }
        return date;
    }

    /**
     * 将Quartz Cron表达式转换为日期
     *
     * @param cron
     * @return
     */
    public static Date getDateEveryYear(final String cron) {
        if (cron == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(CRON_DATE_FORMAT_EVERY);
        Date date = null;
        try {
            date = sdf.parse(cron);
        } catch (ParseException e) {
            return null;// 此处缺少异常处理,自己根据需要添加
        }
        return date;
    }

    public static void main(String[] args) {
        Date now = new Date();
        System.out.println(CronDateUtils.getCron(now));


        String cron = "42 57 19 20 06 ? 2019";
        Date cronDate = CronDateUtils.getDate(cron);

        System.out.println(DateUtils.formatDateTime(cronDate));

        System.out.println("====================================");

        String cron1 = "42 57 19 20 06 ? *";
        Date cronDate1 = CronDateUtils.getDateEveryYear(cron1);
        System.out.println(cronDate1);
    }

}
